package com.cstar.learnlang.PageControllers;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.cstar.learnlang.DataForms.LoginDataForm;
import com.cstar.learnlang.DataForms.PasswordResetDataForm;
import com.cstar.learnlang.DataForms.UserInfoObj;
import com.cstar.learnlang.RowMappers.UserInfoObjRowMapper;

@Controller
@RequestMapping(value={"/loginFormPost", "/loginPage"})
@SessionAttributes
public class LoginPageController {
	private static final Logger logger = LoggerFactory.getLogger(LoginPageController.class);
	@Autowired
	private JdbcTemplate jdbcRegisterInfoTemplate;
	@Autowired
	private HomePageController homePageController;
	@Autowired
	private ReloadableResourceBundleMessageSource messageSource;
	@RequestMapping(value = "/loginPage", method = RequestMethod.GET)
	public String loginPage(HttpServletRequest request,
			HttpServletResponse response,
    		HttpSession session,
			@RequestParam(value="logout", required=false) String logout, 
			@RequestParam(value="ln", required=false) String ln) {
		homePageController.ProcessLanguageSwitchAndLogout(request, response, session, ln, logout);
		session.setAttribute("pageName", "login");
		return "loginPage";
	} // loginPage
	@RequestMapping(value = "/loginPage", method = RequestMethod.DELETE)
	public String loginPageDeleteUser(
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session,
			@RequestParam(value="email") String email,
			@RequestParam(value="pass") String pass) {
        System.out.println("loginPageDeleteUser email:" + email + " password:" + pass);
		homePageController.ProcessLanguageSwitchAndLogout(request, response, session, null, null);
		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		String sql;
		int anyMatch;
		sql = "SELECT * FROM USER_INFO WHERE EMAIL = ?";
		@SuppressWarnings("unchecked")
		List<UserInfoObj> userInfo = jdbcRegisterInfoTemplate.query(sql, new String[] {email}, new UserInfoObjRowMapper());
        System.out.println("sql - " + sql);
		if (userInfo.size() == 0) {
			session.setAttribute ("serverReturnCode", "Error:User is not deleted, check email and password");
		} else {
			// First reset vocabulary table user_id to 0
			sql = "UPDATE VOCABULARY_LIST SET USER_ID=0 WHERE USER_ID = ?";
			jdbcRegisterInfoTemplate.update(sql, new Object[] {userInfo.get(0).getRowId()});
			// Now we can delete the user
			sql = "DELETE FROM USER_INFO WHERE EMAIL = ? AND PASSWORD_MD5 = ?";
			jdbcRegisterInfoTemplate.update(sql, new Object[] {email, md5.encodePassword(pass, "")});
	        System.out.println("sql - " + sql);
			sql =  "SELECT COUNT(*) FROM USER_INFO WHERE EMAIL = ?";
			anyMatch = jdbcRegisterInfoTemplate.queryForInt(sql, new String[] {email});
	        System.out.println("sql - " + sql);
			if (anyMatch != 0) {
				session.setAttribute ("serverReturnCode", "Error:User is not deleted, check email and password");
			} else {
				session.setAttribute ("serverReturnCode", "Success:User is deleted successfully");
			} // if
		} // if
		return "redirect:/homePage";
	} // loginPageDeleteUser
	@RequestMapping(value="/loginFormPost", method = RequestMethod.POST)
    public String loginFormPost(
    		HttpServletRequest request,
    		HttpSession session,
    		@ModelAttribute("loginFormData")LoginDataForm loginFormData, 
    		BindingResult result) {
        System.out.println("email:" + loginFormData.getEmail() + "password:" + loginFormData.getPassword());
		String sql = "SELECT * FROM USER_INFO WHERE EMAIL = ? AND PASSWORD_MD5 = ?";
		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		@SuppressWarnings("unchecked")
		List<UserInfoObj> anyMatch = jdbcRegisterInfoTemplate.query(sql, new Object[] { 
				loginFormData.getEmail(), md5.encodePassword(loginFormData.getPassword(), "") 
			}, new UserInfoObjRowMapper());
        System.out.println("loginFormPost anyMatch:" + anyMatch.size());
		if (anyMatch.size() != 1) {
			session.setAttribute ("serverReturnCode", "Error:Email address or password is wrong");
			return "redirect:/loginPage";
		} // if
		session = request.getSession(true);
		session.setAttribute("loginOkay", "1");
		session.setAttribute("username", loginFormData.getEmail());
		session.setAttribute("userid", anyMatch.get(0).getRowId());
		return "redirect:/homePage";
    } // loginFormPost
	@ModelAttribute("loginFormData")
    public LoginDataForm getLoginDataForm() {
        return new LoginDataForm();
    } // getLoginDataForm
} // LoginPageController 
